<?php
namespace App\Services\Account;
use App\Common\ResponseCode;
use App\Exceptions\BusinessException;
use App\Params\H5\AccountRechargeLogParams;
use App\Params\H5\AccountRechargeParams;
use App\Repository\AccountRepository;
use App\Repository\CustomerRepository;
use App\Services\BaseService;
use App\Traits\Calculator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 账户相关业务类
 *
 * @author WangBin
 * @date 2021-09-24
 * @package App\Http\Services
 */
class AccountService extends BaseService
{
    use Calculator;

    /**
     * 获取充值套餐
     *
     * @return array
     * @throws
     */
    public function getPlan()
    {
        return [
            [
                'plan_id' => '10001',
                'plan_name' => '充500送50',
                'money' => 500,
                'gift_money' => 50
            ],
            [
                'plan_id' => '10002',
                'plan_name' => '充1000送150',
                'money' => 1000,
                'gift_money' => 150
            ]
        ];
    }

    /**
     * 账户充值
     *
     * @param AccountRechargeParams $params
     * @return mixed
     * @throws BusinessException
     */
    public function recharge(AccountRechargeParams $params)
    {
        $customer = CustomerRepository::getInstance()->getById($params->getCustomerId());
        if(is_null($customer)) {
            throw new BusinessException(ResponseCode::CUSTOMER_NOT_FOUND);
        }
        if(empty($params->getPlanId()) && empty($params->getAmount())) {
            throw new BusinessException(ResponseCode::PARAM_ILLEGAL);
        }
        // 获取充值套餐
        $plan = $this->getPlan();
        $planIds = array_values(array_column($plan, 'plan_id'));
        if($params->getPlanId() && !in_array($params->getPlanId(), $planIds)) {
            throw new BusinessException(ResponseCode::ACCOUNT_PLAN_ERROR);
        }
        // 客户当前余额
        $balance = $customer->balance;
        $params->setAmount(number_format($params->getAmount(), 0, '', ''));
        try {
            DB::beginTransaction();
            if($params->getPlanId()) {
                $plan = collect($plan)->firstWhere('plan_id', $params->getPlanId());
                $amount = $this->addNum($plan['money'], $plan['gift_money']);
                CustomerRepository::getInstance()->updateBalance($params->getCustomerId(), $amount);
            } else {echo $params->getAmount();
                // 单次充值不得大于 1000
                if($this->compare($params->getAmount(), 1000) == 1) {
                    throw new BusinessException(ResponseCode::ACCOUNT_RECHARGE_AMOUNT_ERROR);
                }
                $amount = $params->getAmount();
                CustomerRepository::getInstance()->updateBalance($params->getCustomerId(), $amount);
            }
            $customer->refresh(); // 刷新客户信息
            // 记录充值记录
            $data = [
                'customer_id' => $params->getCustomerId(),
                'customer_name' => $customer->nickname,
                'balance_before' => $balance,
                'recharge' => $amount,
                'balance' => $customer->balance,
                'status' => 1
            ];
            AccountRepository::getInstance()->save($data);
            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            Log::error("[客户充值] 出错：{$exception->getMessage()}");
            throw new BusinessException(ResponseCode::ACCOUNT_RECHARGE_FAIL);
        }
        return $customer->refresh()->balance;
    }

    /**
     * 获取客户充值记录列表
     *
     * @param AccountRechargeLogParams $params
     * @return array
     */
    public function getLogList(AccountRechargeLogParams $params)
    {
        $logs = AccountRepository::getInstance()->getList($params->toArray());
        return $this->toList($logs, $params->getPage(), $params->getPageSize());
    }
}
